<!-- 服务管理列表 -->
<template>
  <div>
    <myDivider name="服务管理"></myDivider>
    <div class="top">
      <el-select v-model="keyType" placeholder="筛选机关/机构" @change="TopSelectChange">
        <el-option label="所有" value=""></el-option>
        <el-option label="机关" value="1"></el-option>
        <el-option label="机构" value="2"></el-option>
      </el-select>
      <el-input class="Keyinput" maxlength="20" v-model="keyName" placeholder="输入机关机构名称"></el-input>
      <el-button class="searchForBtn" @click="SouSuo" type="primary" icon="el-icon-search">搜索</el-button>
      <el-button class="addBtn" type="primary" @click="goAdd" icon="el-icon-plus">添加机关/机构</el-button>
    </div>
    <!-- 表格列表 -->
    <div class="tableBox">
      <el-table :data="tableData" column-key="serviceStatus" ref="tableEl" style="width: 100%"
        @filter-change="filterChange">
        <el-table-column align="center" prop="companyName" label="名称" width="250">
        </el-table-column>
        <el-table-column align="center" prop="oryType" label="类型" width="150">
        </el-table-column>
        <el-table-column :filter-multiple="false" column-key="serviceStatus" align="center" prop="serviceStatus"
          label="服务开通状态" width="150" :filters="filters">
        </el-table-column>
        <el-table-column align="center" prop="serviceTime" label="服务期限">
        </el-table-column>
        <el-table-column align="center" prop="state" label="服务" width="200">
          <template slot-scope="scope">
            <div style="display: flex;align-items: center;justify-content: space-around;">
              <el-button style="display: block;" type="primary" size="mini" @click="openFW(scope.row)">开通服务</el-button>
              <el-button style="display: block;" type="primary" plain size="mini" @click="closeFW(scope.row)">{{
        scope.row.serviceStatus == '已中断' ? '继续服务' : '停止服务' }}</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <span style="cursor: pointer;" @click="ShowBianJi(scope.row)">编辑</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <myPagination :total="total" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>

    <!-- 添加机构 -->
    <div class="AddStyle">
      <el-dialog title="添加机构" :visible.sync="AddShow" width="400px">
        <el-form label-width="80px">
          <el-form-item label="机构类型">
            <el-select v-model="AddVal" placeholder="选择新增机关/机构" @change="AddSelectChange">
              <el-option label="机关" value="机关"></el-option>
              <el-option label="机构" value="机构"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="AddClose">取 消</el-button>
          <el-button type="primary" @click="AddOk">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 开通服务 -->
    <div class="dialogKaiTongFWStyle">
      <el-dialog @close="KTFWclose" title="开通服务" :visible.sync="dialogKaiTongFW" width="650px">
        <el-form :rules="rules" ref="KaiTongFWform" :model="KaiTongFWData" label-width="80px">
          <el-form-item label="机构名称">
            <el-input class="ok" placeholder="请输入机构名称" v-model="KaiTongFWData.companyName" disabled>
            </el-input>
          </el-form-item>
          <el-form-item label="开通时长" prop="Time">
            <el-date-picker @change="KTFWTime" :append-to-body="false" class="ok" v-model="KaiTongFWData.Time"
              type="daterange" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="备注">
            <el-input class="ok" maxlength="200" show-word-limit type="textarea" :rows="2" placeholder="请输入内容" v-model="KaiTongFWData.notes">
            </el-input>
          </el-form-item>
          <el-form-item label="缴费凭证" prop="imgs" class="jfpz">
            <span>*</span>
            <myupload2 ref="myupload2" @getImgList="getImgList" :FileList="[]"></myupload2>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="KaiTongFwNoOk">取 消</el-button>
          <el-button type="primary" @click="KaiTongFwOK">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 停止服务 -->
    <div class="dialogTingZhiStyle">
      <el-dialog title="停止服务" @close="TZFWclose" :visible.sync="dialogTingZhiFW" width="650px">
        <el-form :rules="TingZhirules" ref="TingZhiFWform" :model="TingZhiFWData" label-width="80px">
          <el-form-item label="停止原因" prop="notes">
            <el-input class="ok" type="textarea" maxlength="200" show-word-limit :rows="2" placeholder="请输入内容" v-model="TingZhiFWData.notes">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="TingZhiFwNoOk">取 消</el-button>
          <el-button type="primary" @click="TingZhiFwOK">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 继续服务 -->
    <div class="dialogJiXuStyle">
      <el-dialog @close="JXFWclose" title="继续服务" :visible.sync="dialogJiXuFW" width="650px">
        <el-form :rules="JiXurules" ref="JiXuFWform" :model="JiXuFWData" label-width="80px">
          <el-form-item label="继续原因" prop="notes">
            <el-input class="ok" maxlength="200" show-word-limit type="textarea" :rows="2" placeholder="请输入内容" v-model="JiXuFWData.notes">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="JiXuFwNoOk">取 消</el-button>
          <el-button type="primary" @click="JiXuFwOK">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 编辑 -->
    <div class="BianJiStyle">
      <el-dialog title="编辑" :visible.sync="BianJiShow" width="650px">
        <el-form :rules="BianJirules" ref="BianJiform" :model="BianJiData" label-width="80px">
          <el-form-item label="机构名称">
            <el-input class="ok" placeholder="请输入机构名称" v-model="BianJiData.organizationName" disabled>
            </el-input>
          </el-form-item>
          <el-form-item label="开通记录" v-if="historyVOListShow">
            <div class="eleList">
              <div class="ele" v-for="item, i in BianJiData.historyVOList" :key="i">
                <span>{{ item.serviceStartTime + '~' + item.serviceEndTime }}</span>
                <div>
                  <span v-if="item.notes != null" @click="CKBZ(item)">{{ item.serviceStatus == 3 ? '停止原因' : '查看备注'
                    }}</span>
                  <!-- <img src="@/assets/1.png" alt="" v-if="item.notes != null" @click="CKBZ(item)"> -->
                  <el-image  v-if="item.serviceStatus != 3" ref="BIgimgs" src="#" :preview-src-list="BigImgsData">
                    <span class="ckfjstyle" slot="error" @click="ShowImgs(item)">查看附件</span>
                  </el-image>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="累计缴费">
            <el-input disabled style="width: 50px;" :value="BianJiData.totalYears">
            </el-input>
            <span>年</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="BianJiClose">取 消</el-button>
          <el-button type="primary" @click="BianJiClose">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 备注详情弹窗 -->
    <div class="FujianStyle">
      <el-dialog title="备注详情" :visible.sync="BZDetailShow" width="450px">
        <el-form :model="BZDetailform" :rules="BZDetailrules" ref="BZDetailForm" label-width="100px">
          <el-form-item label="备注" prop="notesDetail">
            <el-input :disabled="FuWuel.serviceStatus == '未开通' || FuWuel.serviceStatus == '已到期'" type="textarea"
              :row="3" maxlength="200" show-word-limit v-model="BZDetailform.notesDetail"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button v-if="FuWuel.serviceStatus != '已中断'" @click="BZDetailShow = false">返回</el-button>
            <el-button v-if="FuWuel.serviceStatus == '已开通' || FuWuel.serviceStatus == '未生效'" type="primary"
              @click="updateNotes">修改</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import myupload2 from '../../components/myupload2'
export default {
  components: {
    myupload2
  },
  data() {
    return {
      BZDetailform: {},
      BZDetailrules: {
        notesDetail: [
          { required: true, message: '请填写备注', trigger: 'blur' },
        ],
      },
      BigImgsData: [],//大图图片列表
      BZDetailShow: false,
      notesDetail: '',
      keyType: '',
      keyName: "",
      tableData: [
      ],
      filters: [
        { text: '未开通', value: '未开通' },
        { text: '已开通', value: '已开通' },
        { text: '已到期', value: '已到期' },
        { text: '已中断', value: '已中断' },
        { text: '未生效', value: '未生效' },
      ],
      // 添加机构/机关弹窗
      AddShow: false,
      AddVal: '',
      // 开通服务 
      dialogKaiTongFW: false,
      KaiTongFWData: {},
      rules: {
        Time: [
          { required: true, message: '请选择开通时长', trigger: 'change' },
        ],
      },
      // 停止服务
      dialogTingZhiFW: false,
      TingZhiFWData: {},
      TingZhirules: {
        notes: [
          { required: true, message: '请填写停止服务的原因', trigger: 'blur' },
        ]
      },
      // 继续服务
      dialogJiXuFW: false,
      JiXuFWData: {},
      JiXurules: {
        notes: [
          { required: true, message: '请填写继续服务的原因', trigger: 'blur' },
        ]
      },
      // 编辑
      BianJiShow: false,
      BianJiData: {},
      BianJirules: {
        notes: [
          { required: true, message: '请填写内容', trigger: 'blur' },
        ]
      },
      // 分页器
      pageNum: 1,
      total: 1,
      activeTableEl: {},
      userid: '',
      pageSize: 10,
      //历史缴费记录
      historyVOListShow: true,
      whenELe: {},// 点击查看备注的那个历史记录元素
      FuWuel: {},//当前的服务元素，用来重新获取最新历史记录
      serviceStatusKey: ''
    }
  },
  mounted() {
    this.userid = sessionStorage.getItem('soa_id')
  },
  activated() {
    this.keyType = ''
    this.keyName = ''
    this.getList()
  },
  deactivated() {
  },
  methods: {
    async updateNotes() {
      let res = await this.$api.orgService.updateNotes({
        "id": this.whenELe.id, //组织id (机关或者机构)
        "notes": this.BZDetailform.notesDetail //修改的备注值
      })
      if (res.code == 200) {
        this.$message({
          message: '备注修改成功',
          type: 'success'
        });
        this.ShowBianJi(this.FuWuel) //刷新页面，显示最新备注
        this.BZDetailShow = false
      } else {
        this.$message({
          message: res.message,
          type: 'warning'
        });
      }
    },
    ShowImgs(item) {
      console.log(item);
      this.BigImgsData = JSON.parse(item.paymentVoucherPictures)
      setTimeout(() => {
        this.$refs.BIgimgs[0].clickHandler()
      }, 500)
    },
    CKBZ(data) {//点击查看备注
      console.log(data, '点击备注按钮');
      this.whenELe = data
      this.BZDetailShow = true
      this.$set(this.BZDetailform, 'notesDetail', data.notes)
    },
    KTFWTime(val) { //开通服务时间选择规则
      if (val[0] === val[1]) {
        this.$message.error('无法选择同一天')
        this.$set(this.KaiTongFWData, 'Time', '')
        return
      }
      let a = val[0].slice(5)
      let b = val[1].slice(5)
      if (a === b) {

      } else {
        this.$message.error('选择失败，只能选择整年！')
        this.$set(this.KaiTongFWData, 'Time', '')
      }
    },
    TZFWclose() {
      this.$nextTick(() => {
        this.$refs['TingZhiFWform'].clearValidate()
      })
      this.$set(this.TingZhiFWData, 'notes', '')
    },
    JXFWclose() {
      this.$nextTick(() => {
        this.$refs['JiXuFWform'].clearValidate()
      })
      this.$set(this.JiXuFWData, 'notes', '')
    },
    KTFWclose() {
      console.log('qwdqwdq');
      this.$nextTick(() => {
        this.$refs['KaiTongFWform'].clearValidate()
      })
      this.$refs.myupload2.clear()
      this.$refs.myupload2.aaaaaaaa()
      this.$set(this.KaiTongFWData, 'Time', '')
      this.$set(this.KaiTongFWData, 'notes', '')
    },
    showImg(val) {
      console.log(val, '当前的');
      let arr = val.paymentVoucherPictures.slice(1, -1).split(',')
      arr.forEach(el => {
        let url = el.slice(1, -1)
        window.open(url, '_blank');
      })
    },

    async filterChange(e) {
      if (e.serviceStatus.length == 0) {
        this.serviceStatusKey = ''
        this.pageNum = 1
        this.getList()
        return
      }
      switch (e.serviceStatus[0]) {
        case '未开通':
          this.serviceStatusKey = 0
          break
        case '已开通':
          this.serviceStatusKey = 1
          break
        case '已到期':
          this.serviceStatusKey = 2
          break
        case '已中断':
          this.serviceStatusKey = 3
          break
        case '未生效':
          this.serviceStatusKey = 4
          break
      }
      this.pageNum = 1
      this.getList()
    },
    pageSizeChange(e) {
      this.pageNum = 1
      this.pageSize = e
      this.getList()
    },
    PageChange(e) {
      this.pageNum = e
      this.getList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getList()
    },
    async getList() {
      let params = {
        "name": this.keyName, //机构名称
        "serviceStatus": this.serviceStatusKey, //服务开通状态 默认:0未开通 1已开通 2已到期 3已中断 4未生效
        "orgType": this.keyType, //组织类型 1:机关 2:机构
        "serviceStartTime": "", //服务开始时间
        "serviceEndTime": "", //服务到期时间
        "pageNum": this.pageNum,
        "pageSize": this.pageSize
      }
      let res = await this.$api.orgService.getorgServiceList(params)
      let arr = ['未开通', '已开通', '已到期', '已中断', '未生效']
      if(res.list.length==0 && this.pageNum!=1){
        this.pageNum =1
        this.getList()
        return
      }
      this.total = res.total
      this.tableData = []
      res.list.forEach(el => {
        this.tableData.push({
          id: el.id,
          companyName: el.companyName,
          oryType: el.orgType == 1 ? '机关' : "机构",
          serviceStatus: arr[el.serviceStatus],
          serviceTime: el.serviceStartTime == null ? '' : el.serviceStartTime + '~' + el.serviceEndTime
        })
      });
    },
    async ShowBianJi(row) {
      this.FuWuel = row
      console.log(row.serviceStatus, '点击的服务');
      // if (row.serviceStatus == '已中断') {
      //   this.$message('已中断不可编辑');
      //   // return
      // }
      if (row.serviceStatus == '未开通') {
        this.$message('暂未开通服务');
        return
      }
      let res = await this.$api.orgService.orgServiceDetail(row.id, row.oryType == '机关' ? '1' : '2')

      this.BianJiData = res.data
      console.log(this.BianJiData, '详情');
      if (this.BianJiData.historyVOList.length < 1) {
        this.historyVOListShow = false
      } else {
        this.historyVOListShow = true
      }
      this.BianJiShow = true
    },
    // 选择图片后返回的图片列表
    getImgList(val) {
      console.log(val, 'val');
      this.KaiTongFWData.paymentVoucherPictures = val
    },
    // 顶部下拉选择类型
    TopSelectChange() {
      this.getList()
    },

    //点击新增机构/机关，弹窗显示
    goAdd() {
      this.AddShow = true
    },
    AddSelectChange(e) {
      this.AddVal = e
    },
    // 添加机构弹窗 取消
    AddClose() {
      this.AddShow = false
    },
    // 添加机构弹窗 确认
    AddOk() {
      this.AddShow = false
      console.log(this.AddVal, 'this.AddVal')
      if (this.AddVal == '机关') {
        this.$router.push('/agency/agencyInsert')
      } else if (this.AddVal == '机构') {
        this.$router.push('/institution/institutionInsert')
      }
    },
    // 点击开通服务按钮
    openFW(val) {
      sessionStorage.setItem('serviceEle', JSON.stringify(val))
      this.activeTableEl = val
      this.KaiTongFWData.companyName = val.companyName
      this.dialogKaiTongFW = true
    },
    // 点击继续服务/停止服务
    closeFW(val) {
      this.activeTableEl = val
      switch (val.serviceStatus) {
        case '未开通':
          this.$message({
            message: '服务未开通，无法中断服务',
            type: 'warning'
          });
          break
        case '已开通':
          // 停止服务弹窗打开
          this.dialogTingZhiFW = true
          break
        case '已到期':
          this.$message({
            message: '服务已到期，无法中断服务',
            type: 'warning'
          });
          break
        case '已中断':
          // 继续服务弹窗打开
          this.dialogJiXuFW = true
          break
        case '未生效':
          this.$message({
            message: '未生效',
            type: 'warning'
          });
          break
      }

    },
    // 开通服务点击 取消
    KaiTongFwNoOk() {
      this.dialogKaiTongFW = false
    },
    // 开通服务点击 确认
    KaiTongFwOK() {
      this.$refs['KaiTongFWform'].validate(async (valid) => {
        if (valid) {
          if (this.KaiTongFWData.paymentVoucherPictures == undefined || this.KaiTongFWData.paymentVoucherPictures.length < 1) {
            this.$message.error('请上传您的缴费凭证');
            return
          }
          let params = {
            "orgId": this.activeTableEl.id, //组织id (机关或者机构)
            "orgType": this.activeTableEl.oryType == '机关' ? 1 : 2, //组织类型 (1机关/2机构)
            "notes": this.KaiTongFWData.notes,
            "operatorId": this.userid, //(当前登录用户的id)
            "paymentVoucherPictures": JSON.stringify(this.KaiTongFWData.paymentVoucherPictures), //图片url按照顺序拼接的json字符串
            "serviceStatus": 1, //服务开通状态 默认:0未开通 1已开通 2已到期 3已中断 4未生效 此接口默认传1 不传其他值 
            "serviceStartTime": this.KaiTongFWData.Time[0], //服务开始时间
            "serviceEndTime": this.KaiTongFWData.Time[1] //服务到期时间
          }
          let res = await this.$api.orgService.availableService(params)
          console.log(res, '开通服务接口');
          if (res.code == 200) {
            this.$message({
              message: '开通成功',
              type: 'success'
            });
            this.dialogKaiTongFW = false
            this.getList()
            for (let a in this.KaiTongFWData) {
              this.KaiTongFWData[a] = null
            }
          } else {
            this.$message.error(res.message);
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 停止服务的 取消
    TingZhiFwNoOk() {
      console.log('停止服务的取消');
      this.dialogTingZhiFW = false
    },
    // 停止服务的 确认
    TingZhiFwOK() {
      this.$refs['TingZhiFWform'].validate(async (valid) => {
        if (valid) {
          let params = {
            "orgId": this.activeTableEl.id, //组织id (机关或者机构)
            "orgType": this.activeTableEl.oryType == '机关' ? '1' : '2', //组织类型 (1机关/2机构)
            "notes": this.TingZhiFWData.notes, //停止服务的原因
            "operatorId": this.userid, //(当前登录用户的id)
            "serviceStatus": 3 //中止服务:3 继续服务:1
          }
          console.log(params, '验证通过')
          let res = await this.$api.orgService.discontinueService(params)
          if (res.code == 200) {
            this.$message({
              message: '终止成功',
              type: 'success'
            });
            this.dialogTingZhiFW = false
            this.getList()
            //停止服务的内容
            this.TingZhiFWData.notes = ''
          }

          console.log(res, '终止服务');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 继续服务的 取消
    JiXuFwNoOk() {
      console.log('继续服务的取消');
      this.dialogJiXuFW = false
    },
    // 继续服务的 确认
    JiXuFwOK() {
      this.$refs['JiXuFWform'].validate(async (valid) => {
        if (valid) {
          let params = {
            "orgId": this.activeTableEl.id, //组织id (机关或者机构)
            "orgType": this.activeTableEl.oryType == '机关' ? '1' : '2', //组织类型 (1机关/2机构)
            "notes": this.JiXuFWData.notes, //停止服务的原因
            "operatorId": this.userid, //(当前登录用户的id)
            "serviceStatus": 1 //中止服务:3 继续服务:1
          }
          let res = await this.$api.orgService.discontinueService(params)
          if (res.code == 200) {
            this.$message({
              message: '继续服务成功',
              type: 'success'
            });
            this.dialogJiXuFW = false
            this.getList()
            //情况继续服务的内容
            this.JiXuFWData.notes = ''
          }
          console.log(this.activeTableEl, '继续服务验证通过')
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 编辑弹窗点击 取消
    BianJiClose() {
      console.log('编辑弹窗点击 取消');
      this.BianJiShow = false
    },
    // 编辑弹窗点击 确认
    BianJiOk() {
      this.$refs['BianJiform'].validate(async (valid) => {
        if (valid) {


          // console.log(res, '修改成功');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
}
</script>

<style lang="less" scoped>
.top {
  width: 100%;
  padding: 20px 30px;
  box-sizing: border-box;
  position: relative;
  display: flex;
  position: relative;

  .Keyinput {
    width: 200px;
    margin: 0 15px;
  }

  .searchForBtn {}

  .addBtn {
    position: absolute;
    right: 10px;
  }

}

.tableBox {
  margin-top: 50px;

  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
      }
    }
  }
}

.ok {
  width: 500px;
}

.BianJiStyle {
  .eleList {
    width: 500px;

    .ele {
      margin: 5px 0;
      padding: 0 20px;
      box-sizing: border-box;
      width: 100%;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      >div {
        display: flex;
        justify-content: space-between;
        align-items: center;

        >span {
          color: rgb(13, 166, 255);
          cursor: pointer;
        }

        .ckfjstyle {
          color: rgb(13, 166, 255);
          margin-left: 20px;
          cursor: pointer;
        }
      }


      // span {
      //   &:nth-child(2) {  
      //     cursor: pointer;
      //   }
      // }
    }
  }
}

.FujianStyle {}


.dialogKaiTongFWStyle {
  .jfpz {
    position: relative;

    .el-form-item__content {
      >span {
        position: absolute;
        left: -80px;
        top: 0;
        color: #F56C6C;
      }
    }

  }

  /deep/ .el-date-range-picker {
    .el-date-range-picker__header {
      button {
        color: black;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }
}

// .imgstyle {
//   width: 80px;
//   height: 80px;
//   display: flex;
//   flex-direction: column;
//   align-items: center;
//   border: 2px dashed black;
//   border-radius: 15px;
//   >i{
//     transform: scale(2);
//     margin: 15px 0;
//   }
// }// }</style>